package de.grosjohann.android.feuerwehr.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import de.grosjohann.android.feuerwehr.R;
import de.grosjohann.android.feuerwehr.util.PrefsUtil;

public final class IntentServiceFacade {

  public static void startRepeating(Context ctx, Class<?> clazz) {
    int interval = PrefsUtil.getInt(ctx, R.string.prefKeyInterval, R.string.prefDefaultInterval);
    startRepeating(ctx, clazz, interval * PrefsUtil.MILLI_SEC_OF_MINUTE);
  }

  public static void startRepeating(Context ctx, Class<?> clazz, int interval) {
    AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(ctx, clazz);
    PendingIntent pendingIntent = PendingIntent.getService(ctx, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), interval, pendingIntent);
  }

  public static void stopRepeating(Context ctx, Class<?> clazz) {
    AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(ctx, clazz);
    PendingIntent pendingIntent = PendingIntent.getService(ctx, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
    alarmManager.cancel(pendingIntent);
  }

  public static void restartRepeating(Context ctx, Class<?> clazz) {
    stopRepeating(ctx, clazz);
    startRepeating(ctx, clazz);
  }

  public static void startOnce(Context ctx, Class<?> clazz) {
    Intent intent = new Intent(ctx, clazz);
    ctx.startService(intent);
  }

}
